#include "backtestwidget.h"
#include <QStackedWidget>
BackTestWidget::BackTestWidget(QWidget *parent)
    : QWidget{parent}
{

    setWindowTitle("加密货币量化回测框架");
    setGeometry(100, 100, 1400, 900);

    // 初始化策略和回测引擎
    m_strategy = new SMAStrategy(5, 20);
    m_minStrategy=new MineStrategy();

    m_backtestEngine = new BacktestEngine;

    // 创建主部件和布局
    QWidget* centralWidget = new QWidget(this);
    QVBoxLayout* mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setSpacing(0);
    //mainLayout->setContentsMargins(0,0,0,0);

    // 创建控制区域
    createControlPanel(mainLayout);

    // 创建标签页
    m_tabWidget = new QTabWidget();
    mainLayout->addWidget(m_tabWidget);
    mainLayout->setStretch(0,1);
    mainLayout->setStretch(1,3);
    mainLayout->setStretch(2,6);



    // 创建各个标签页
    createChartTab();
    createTradesTab();
    createResultsTab();

    /*********************设置回测窗口************************/
    //setCentralWidget(centralWidget);


    QHBoxLayout*global_lay=new QHBoxLayout(this);
    global_lay->setSpacing(0);
    global_lay->setContentsMargins(0,0,0,0);
    global_lay->addWidget(centralWidget);

    // 生成测试数据
   // generateTestData();


}

BackTestWidget::~BackTestWidget()
{
    delete m_strategy;
    delete  m_minStrategy;
    delete m_backtestEngine;
}

void BackTestWidget::loadData()
{
    QString filePath = QFileDialog::getOpenFileName(this, "选择数据文件", "", "CSV文件 (*.csv)");
    if (filePath.isEmpty()) return;

    m_data = DataLoader::loadFromCSV(filePath);
    if (m_data.isEmpty()) {
        QMessageBox::warning(this, "警告", "未能加载数据或数据为空");
        return;
    }

    m_dataFileLabel->setText(QFileInfo(filePath).fileName());
    QMessageBox::information(this, "成功", QString("已加载 %1 条数据").arg(m_data.size()));

    // 显示K线图
    updateChart();
}

void BackTestWidget::generateTestData()
{
    int days = 30;
    m_data = DataLoader::generateTestData(days);
    m_dataFileLabel->setText(QString("测试数据 (%1天)").arg(days));
    updateChart();
    QMessageBox::information(this, "成功", QString("已生成 %1 条测试数据").arg(m_data.size()));
}

void BackTestWidget::updateIconSizes()
{
    int iconSize = m_iconSizeSpin ? m_iconSizeSpin->value() : 24;

    // 更新控制面板按钮的图标尺寸
    for (QPushButton* btn : m_iconButtons) {
        if (btn) btn->setIconSize(QSize(iconSize, iconSize));
    }

    // 更新图表中买卖信号的 marker 大小（与图标大小成比例）
    if (m_buySeries) m_buySeries->setMarkerSize(iconSize * 0.6);
    if (m_sellSeries) m_sellSeries->setMarkerSize(iconSize * 0.6);
}

void BackTestWidget::runBacktest()
{
    if (m_data.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先加载数据");
        return;
    }

    // 更新策略参数
    int shortPeriod = m_shortPeriodSpin->value();
    int longPeriod = m_longPeriodSpin->value();
    if (shortPeriod >= longPeriod) {
        QMessageBox::warning(this, "警告", "短期周期必须小于长期周期");
        return;
    }

    dynamic_cast<SMAStrategy*>(m_strategy)->setParameters(shortPeriod, longPeriod);

    // 设置初始资金并运行回测
    double initialBalance = m_initialBalanceSpin->value();
    m_backtestEngine->setInitialBalance(initialBalance);
    m_backtestEngine->setData(m_data);

    bool success = m_backtestEngine->run();
    if (success) {
        // 更新图表、交易记录和结果
        updateChart(true);
        updateTradesTable();
        updateResults();

        QMessageBox::information(this, "成功",
                                 QString("回测完成！\n总收益率: %1%")
                                     .arg(m_backtestEngine->getTotalReturn(), 0, 'f', 2));
    } else {
        QMessageBox::warning(this, "失败", "回测失败");
    }
}

void BackTestWidget::createControlPanel(QVBoxLayout *mainLayout)
{
        QGroupBox* controlGroup = new QGroupBox("控制中心");
        QVBoxLayout* controlLayout = new QVBoxLayout(controlGroup);

        // 回测按钮
        QPushButton* backtestButton = new QPushButton("运行回测");
        backtestButton->setMinimumWidth(100);
        backtestButton->setStyleSheet("QPushButton {\
                            color:white; \
                          border: none; \
                          width: 30px; \
                          height: 30px; \
                            background-color:gray; \
                          border-radius: 4px; \
                          } \
                          QPushButton:hover { \
                          background-color: #555555; \
                          }");
        //backtestButton->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; font-weight: bold; padding: 8px; }");
        connect(backtestButton, &QPushButton::clicked, this, &BackTestWidget::runBacktest);
        //controlLayout->addWidget(backtestButton);




        // 数据操作区域
        QHBoxLayout* dataLayout = new QHBoxLayout();
        QPushButton* loadButton = new QPushButton("加载CSV数据");
        loadButton->setMinimumWidth(100);
        loadButton->setStyleSheet("QPushButton {\
                            color:white; \
                          border: none; \
                          width: 30px; \
                          height: 30px; \
                            background-color:gray; \
                          border-radius: 4px; \
                          } \
                          QPushButton:hover { \
                          background-color: #555555; \
                          }");

        QPushButton* testDataButton = new QPushButton("生成测试数据");
        testDataButton->setMinimumWidth(100);
        testDataButton->setStyleSheet("QPushButton {\
                            color:white; \
                          border: none; \
                          width: 30px; \
                          height: 30px; \
                            background-color:gray; \
                          border-radius: 4px; \
                          } \
                          QPushButton:hover { \
                          background-color: #555555; \
                          }");
        connect(loadButton, &QPushButton::clicked, this, &BackTestWidget::loadData);
        connect(testDataButton, &QPushButton::clicked, this, &BackTestWidget::generateTestData);

        //combox用于选择策略

        QComboBox*combox_strategy=new QComboBox;
        combox_strategy->addItems(QStringList()<<"SMA策略"<<"Mine策略");
        combox_strategy->setMinimumWidth(100);
        combox_strategy->setStyleSheet(
            "QComboBox {"
            "color:white;"\
            "background-color: gray;" // 背景颜色
            "border: 1px solid #d3d3d3;"  // 边框
            "border-radius: 5px;"         // 边框圆角
            "padding: 5px;"               // 内边距
            "selection-background-color: #c0c0c0;" // 选中项背景色
            "}"
            "QComboBox::drop-down {"
            "subcontrol-origin: padding;"
            "subcontrol-position: top right;"
            "width: 12px;" // 下拉按钮的宽度
            "background-color:green;"\
            "color:green;"\
            "}"
            "QComboBox QAbstractItemView {" // 下拉列表项的样式
            "selection-background-color: #e0e0e0;" // 选中项背景色
            "background: #ffffff;" // 下拉列表背景色
            "}"
            );


        //设置QcomBox信号槽 选择策略
        connect(combox_strategy,&QComboBox::currentIndexChanged,this,&BackTestWidget::selectStrategy);

        //用于设置资金费率
        QComboBox*combox_fee=new QComboBox;
        combox_fee->addItems(QStringList()<<"0.001"<<"0.0009");
        combox_fee->setMinimumWidth(100);
        combox_fee->setStyleSheet(
            "QComboBox {"
            "color:white;"\
            "background-color: gray;" // 背景颜色
            "border: 1px solid #d3d3d3;"  // 边框
            "border-radius: 5px;"         // 边框圆角
            "padding: 5px;"               // 内边距
            "selection-background-color: #c0c0c0;" // 选中项背景色
            "}"
            "QComboBox::drop-down {"
            "subcontrol-origin: padding;"
            "subcontrol-position: top right;"
            "width: 12px;" // 下拉按钮的宽度
            "background-color:green;"\
            "color:green;"\
            "}"
            "QComboBox QAbstractItemView {" // 下拉列表项的样式
            "selection-background-color: #e0e0e0;" // 选中项背景色
            "background: #ffffff;" // 下拉列表背景色
            "}"
            );


        //设置QcomBox信号槽 选择费率
        //connect(combox_fee,&QComboBox::currentIndexChanged,this,&BackTestWidget::selectStrategy);



        m_dataFileLabel = new QLabel("未加载数据");
        m_dataFileLabel->setStyleSheet("QLabel { background-color: #f0f0f0; padding: 5px; }");
        dataLayout->addWidget(backtestButton);
        dataLayout->addWidget(loadButton);
        dataLayout->addWidget(testDataButton);
         dataLayout->addWidget(combox_strategy);
        dataLayout->addWidget(combox_fee);


        dataLayout->addWidget(m_dataFileLabel);

        dataLayout->addStretch();
        controlLayout->addLayout(dataLayout);




        widget_strategy=new QStackedWidget(this);
       // widget_strategy->setFixedHeight(80);
        widget_strategy->setCurrentIndex(0);




        //QHBoxLayout*layout_strategy=new QHBoxLayout(widget_strategy);


        // 策略参数设置
        QGroupBox* strategyGroup = new QGroupBox("策略参数 (SMA交叉策略)");


        QFormLayout* paramsLayout = new QFormLayout(strategyGroup);

        m_shortPeriodSpin = new QSpinBox();
        m_shortPeriodSpin->setMaximumWidth(100);
        m_shortPeriodSpin->setStyleSheet("QSpinBox {\
        border: 1px solid black;\
        color:white; \
        border-radius: 2px;\
        background: #444444;\
        padding-right: 15px; /* 为箭头预留空间 */\
        }\
        QSpinBox:hover {\
        border-color: #4e51bf;\
        }\
");
        m_shortPeriodSpin->setRange(1, 100);
        m_shortPeriodSpin->setValue(5);
        m_shortPeriodSpin->setToolTip("短期移动平均线周期");

        m_longPeriodSpin = new QSpinBox();
        m_longPeriodSpin->setMaximumWidth(100);
        m_longPeriodSpin->setStyleSheet("QSpinBox {\
        border: 1px solid black;\
        color:white; \
        border-radius: 2px;\
        background: #444444;\
        padding-right: 15px; /* 为箭头预留空间 */\
        }\
        QSpinBox:hover {\
        border-color: #4e51bf;\
        }\
");
        m_longPeriodSpin->setRange(2, 200);
        m_longPeriodSpin->setValue(20);
        m_longPeriodSpin->setToolTip("长期移动平均线周期");

        m_initialBalanceSpin = new QDoubleSpinBox();
        m_initialBalanceSpin->setStyleSheet("QDoubleSpinBox {\
        border: 1px solid black;\
        color:white; \
        border-radius: 2px;\
        background: #444444;\
        padding-right: 15px; /* 为箭头预留空间 */\
        }\
        QDoubleSpinBox:hover {\
        border-color: #4e51bf;\
        }\
");
        m_initialBalanceSpin->setMaximumWidth(100);
        m_initialBalanceSpin->setRange(100, 1000000);
        m_initialBalanceSpin->setValue(10000);
        m_initialBalanceSpin->setSuffix(" USD");
        m_initialBalanceSpin->setToolTip("初始投资资金");



        m_iconSizeSpin = new QSpinBox();
        m_iconSizeSpin->setStyleSheet("QSpinBox {\
        border: 1px solid black;\
        color:white; \
        border-radius: 2px;\
        background: #444444;\
        padding-right: 15px; /* 为箭头预留空间 */\
        }\
        QSpinBox:hover {\
        border-color: #4e51bf;\
        }\
");
        m_iconSizeSpin->setMaximumWidth(100);
        m_iconSizeSpin->setRange(8, 128);
        m_iconSizeSpin->setValue(16);
        m_iconSizeSpin->setToolTip("调整按钮图标和信号标记的大小");


        paramsLayout->addRow("短期均线周期:", m_shortPeriodSpin);
        paramsLayout->addRow("长期均线周期:", m_longPeriodSpin);
        paramsLayout->addRow("初始资金:", m_initialBalanceSpin);
        paramsLayout->addRow("图标大小设置:",m_iconSizeSpin);

        //**********************添加第一页widget*****************************
        QWidget*smapage=new QWidget;
        QHBoxLayout*smaLayout=new QHBoxLayout(smapage);
        smaLayout->addWidget(strategyGroup);
        widget_strategy->addWidget(smapage);

          //**********************添加第二页widget*****************************

        QWidget*minepage=new QWidget;
        QHBoxLayout*minestrategy=new QHBoxLayout(minepage);
        // minestrategy->addWidget(new QLabel("Min Strategy"));
         widget_strategy->addWidget(minepage);


        //widget_strategy->addWidget()
        //layout_strategy->addWidget();
        controlLayout->addWidget(widget_strategy);
        connect(combox_strategy,&QComboBox::currentIndexChanged,[&](int index){
            widget_strategy->setCurrentIndex(index);
        });




        // --------- 图标相关控制（可缩放） ---------
        // 在数据操作区域下添加图标大小控制，并把常用按钮使用系统图标
        // 创建图标大小控制（默认 24px）
        //QHBoxLayout* iconLayout = new QHBoxLayout();

        //QLabel* iconSizeLabel = new QLabel("图标大小 (px):");

        //iconLayout->addWidget(iconSizeLabel);
        //iconLayout->addWidget(m_iconSizeSpin);
        //iconLayout->addStretch();


        //controlLayout->addLayout(iconLayout);

        // 为常用按钮设置系统标准图标并缓存按钮指针，便于统一缩放
        int iconSize = m_iconSizeSpin->value();
        QIcon openIcon = style()->standardIcon(QStyle::SP_DialogOpenButton);
        QIcon newFolderIcon = style()->standardIcon(QStyle::SP_FileDialogNewFolder);
        QIcon playIcon = style()->standardIcon(QStyle::SP_MediaPlay);

        // 设定图标（load/test 按钮是在上面创建的，本函数作用域里有它们）
        // 注意：loadButton 和 testDataButton 在此函数中尚可访问
        // 找到这些按钮并设置图标与缓存
        // 通过遍历 controlGroup 查找所有 QPushButton 更健壮
        QList<QPushButton*> allButtons = controlGroup->findChildren<QPushButton*>();
        for (QPushButton* b : allButtons) {
            if (!b) continue;
            QString text = b->text();
            if (text.contains("加载")) {
                b->setIcon(openIcon);
                m_iconButtons.append(b);
            } else if (text.contains("生成") || text.contains("测试")) {
                b->setIcon(newFolderIcon);
                m_iconButtons.append(b);
            } else if (text.contains("回测") || text.contains("运行")) {
                b->setIcon(playIcon);
                m_iconButtons.append(b);
            } else {
                // 其他按钮也加入，方便统一管理
                m_iconButtons.append(b);
            }
        }

        // 根据初始值设置图标尺寸并绑定调整槽
        for (QPushButton* btn : m_iconButtons) {
            if (btn) btn->setIconSize(QSize(iconSize, iconSize));
        }
        connect(m_iconSizeSpin, qOverload<int>(&QSpinBox::valueChanged), this, &BackTestWidget::updateIconSizes);

        mainLayout->addWidget(controlGroup);
}

void BackTestWidget::createChartTab()
{
    QWidget* chartWidget = new QWidget();
    QVBoxLayout* chartLayout = new QVBoxLayout(chartWidget);

    m_chart = new QChart();
    m_chart->setTitle("K线图与策略信号");
    m_chart->setAnimationOptions(QChart::NoAnimation);
    m_chart->setTheme(QChart::ChartThemeDark);

    // K线系列
    m_candleSeries = new QCandlestickSeries();
    m_candleSeries->setName("K线");
    m_candleSeries->setIncreasingColor(QColor(0, 255, 0));
    m_candleSeries->setDecreasingColor(QColor(255, 0, 0));
    m_candleSeries->setBodyWidth(0.6);
    m_chart->addSeries(m_candleSeries);

    // 买卖信号系列
    m_buySeries = new QScatterSeries();
    m_buySeries->setName("买入信号");
    m_buySeries->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    m_buySeries->setMarkerSize((m_iconSizeSpin ? m_iconSizeSpin->value() : 24) * 0.6);
    //m_buySeries->setColor(QColor(0, 255, 0));
    m_buySeries->setColor(QColor(0,0,255));
    m_buySeries->setBorderColor(QColor(255, 255, 255));
    m_chart->addSeries(m_buySeries);

    m_sellSeries = new QScatterSeries();
    m_sellSeries->setName("卖出信号");
    m_sellSeries->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    m_sellSeries->setMarkerSize((m_iconSizeSpin ? m_iconSizeSpin->value() : 24) * 0.6);
    //
    //m_sellSeries->setColor(QColor(255, 0, 0));
    m_sellSeries->setColor(QColor(255,140, 0));
    m_sellSeries->setBorderColor(QColor(255, 255, 255));
    m_chart->addSeries(m_sellSeries);

    // 均线系列
    m_shortSMASeries = new QLineSeries();
    m_shortSMASeries->setName("短期均线");
    m_shortSMASeries->setColor(QColor(0, 255, 255));
    m_chart->addSeries(m_shortSMASeries);

    m_longSMASeries = new QLineSeries();
    m_longSMASeries->setName("长期均线");
    m_longSMASeries->setColor(QColor(255, 255, 0));
    m_chart->addSeries(m_longSMASeries);

    // 资金曲线系列
    m_balanceSeries = new QLineSeries();
    m_balanceSeries->setName("资金曲线");
    m_balanceSeries->setColor(QColor(0, 255, 0));
    m_chart->addSeries(m_balanceSeries);

    // 创建坐标轴
    m_axisX = new QDateTimeAxis();
    m_axisX->setFormat("MM-dd HH:mm");
    m_axisX->setTitleText("时间");
    m_chart->addAxis(m_axisX, Qt::AlignBottom);

    m_axisY = new QValueAxis();
    m_axisY->setTitleText("价格 (USD)");
    m_axisY->setLabelFormat("%.2f");
    m_chart->addAxis(m_axisY, Qt::AlignLeft);

    m_axisY2 = new QValueAxis();
    m_axisY2->setTitleText("资金 (USD)");
    m_axisY2->setLabelFormat("%.0f");
    m_chart->addAxis(m_axisY2, Qt::AlignRight);

    // 关联系列和坐标轴
    m_candleSeries->attachAxis(m_axisX);
    m_candleSeries->attachAxis(m_axisY);

    m_buySeries->attachAxis(m_axisX);
    m_buySeries->attachAxis(m_axisY);

    m_sellSeries->attachAxis(m_axisX);
    m_sellSeries->attachAxis(m_axisY);

    m_shortSMASeries->attachAxis(m_axisX);
    m_shortSMASeries->attachAxis(m_axisY);

    m_longSMASeries->attachAxis(m_axisX);
    m_longSMASeries->attachAxis(m_axisY);

    m_balanceSeries->attachAxis(m_axisX);
    m_balanceSeries->attachAxis(m_axisY2);

    // 使用自定义 ChartView 支持交互缩放和平移
    m_chartView = new ChartView(m_chart, m_candleSeries);
    m_chartView->setRenderHint(QPainter::Antialiasing);
    chartLayout->addWidget(m_chartView);

    m_tabWidget->addTab(chartWidget, "K线图");
}

void BackTestWidget::createTradesTab()
{
    QWidget* tradesWidget = new QWidget();
    QVBoxLayout* tradesLayout = new QVBoxLayout(tradesWidget);

    m_tradesTable = new QTableWidget();
    m_tradesTable->setColumnCount(7);
    m_tradesTable->setHorizontalHeaderLabels({"时间", "类型", "价格", "数量", "总额", "余额", "利润"});
    m_tradesTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    m_tradesTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tradesTable->setAlternatingRowColors(true);
    tradesLayout->addWidget(m_tradesTable);

    m_tabWidget->addTab(tradesWidget, "交易记录");
}

void BackTestWidget::createResultsTab()
{
    QWidget* resultsWidget = new QWidget();
    QVBoxLayout* resultsLayout = new QVBoxLayout(resultsWidget);

    m_resultsText = new QTextEdit();
    m_resultsText->setReadOnly(true);
    m_resultsText->setFont(QFont("Consolas", 9));
    resultsLayout->addWidget(m_resultsText);

    m_tabWidget->addTab(resultsWidget, "回测结果");
}

void BackTestWidget::updateChart(bool showTrades)
{
    // 清除现有数据
    m_candleSeries->clear();
    m_buySeries->clear();
    m_sellSeries->clear();
    m_shortSMASeries->clear();
    m_longSMASeries->clear();
    m_balanceSeries->clear();

    if (m_data.isEmpty()) return;

    // 添加K线数据
    QVector<double> prices;
    double minPrice = std::numeric_limits<double>::max();
    double maxPrice = std::numeric_limits<double>::lowest();

    for (const auto& candle : m_data) {
        QCandlestickSet* set = new QCandlestickSet();
        set->setTimestamp(candle.timestamp);
        set->setOpen(candle.open);
        set->setHigh(candle.high);
        set->setLow(candle.low);
        set->setClose(candle.close);
        m_candleSeries->append(set);

        prices.append(candle.close);
        minPrice = qMin(minPrice, candle.low);
        maxPrice = qMax(maxPrice, candle.high);
    }

    // 计算并添加均线
    int shortPeriod = m_shortPeriodSpin->value();
    int longPeriod = m_longPeriodSpin->value();

    for (int i = longPeriod - 1; i < m_data.size(); ++i) {
        if (i >= shortPeriod - 1) {
            double shortSMA = std::accumulate(prices.begin() + i - shortPeriod + 1,
                                              prices.begin() + i + 1, 0.0) / shortPeriod;
            m_shortSMASeries->append(m_data[i].timestamp, shortSMA);
        }

        double longSMA = std::accumulate(prices.begin() + i - longPeriod + 1,
                                         prices.begin() + i + 1, 0.0) / longPeriod;
        m_longSMASeries->append(m_data[i].timestamp, longSMA);
    }

    // 显示交易信号和资金曲线
    if (showTrades) {
        const auto& trades = m_backtestEngine->getTrades();

        // 添加资金曲线起点
        double initialBalance = m_initialBalanceSpin->value();
        m_balanceSeries->append(m_data.first().timestamp, initialBalance);

        // 添加交易信号和更新资金曲线
        for (const auto& trade : trades) {
            if (trade.type == TradeRecord::BUY) {
                m_buySeries->append(trade.timestamp, trade.price);
            } else {
                m_sellSeries->append(trade.timestamp, trade.price);
            }
            m_balanceSeries->append(trade.timestamp, trade.balance);
        }

        // 连接到最后一个数据点
        if (!trades.isEmpty()) {
            m_balanceSeries->append(m_data.last().timestamp, trades.last().balance);
        }
    }

    // 设置坐标轴范围
    m_axisX->setMin(QDateTime::fromMSecsSinceEpoch(m_data.first().timestamp));
    m_axisX->setMax(QDateTime::fromMSecsSinceEpoch(m_data.last().timestamp));

    // 设置价格轴范围
    double priceMargin = (maxPrice - minPrice) * 0.1;
    m_axisY->setMin(minPrice - priceMargin);
    m_axisY->setMax(maxPrice + priceMargin);

    // 设置资金轴范围
    if (showTrades && !m_balanceSeries->points().isEmpty()) {
        double minBalance = std::numeric_limits<double>::max();
        double maxBalance = std::numeric_limits<double>::lowest();

        for (const auto& point : m_balanceSeries->points()) {
            minBalance = qMin(minBalance, point.y());
            maxBalance = qMax(maxBalance, point.y());
        }

        double balanceMargin = (maxBalance - minBalance) * 0.1;
        m_axisY2->setMin(minBalance - balanceMargin);
        m_axisY2->setMax(maxBalance + balanceMargin);
    } else {
        double initialBalance = m_initialBalanceSpin->value();
        m_axisY2->setMin(initialBalance * 0.9);
        m_axisY2->setMax(initialBalance * 1.1);
    }
}

void BackTestWidget::updateTradesTable()
{
    const auto& trades = m_backtestEngine->getTrades();
    m_tradesTable->setRowCount(trades.size());

    for (int i = 0; i < trades.size(); ++i) {
        const auto& trade = trades[i];

        QTableWidgetItem* timeItem = new QTableWidgetItem(
            QDateTime::fromMSecsSinceEpoch(trade.timestamp).toString("MM-dd HH:mm")
            );

        QTableWidgetItem* typeItem = new QTableWidgetItem(
            trade.type == TradeRecord::BUY ? "买入" : "卖出"
            );

        QTableWidgetItem* priceItem = new QTableWidgetItem(QString::number(trade.price, 'f', 2));
        QTableWidgetItem* amountItem = new QTableWidgetItem(QString::number(trade.amount, 'f', 6));
        QTableWidgetItem* totalItem = new QTableWidgetItem(QString::number(trade.total, 'f', 2));
        QTableWidgetItem* balanceItem = new QTableWidgetItem(QString::number(trade.balance, 'f', 2));
        QTableWidgetItem* profitItem = new QTableWidgetItem(QString::number(trade.profit, 'f', 2));

        // 设置样式
        if (trade.type == TradeRecord::BUY) {
            typeItem->setBackground(QColor(200, 255, 200));
        } else {
            typeItem->setBackground(QColor(255, 200, 200));
        }

        if (trade.profit >= 0) {
            profitItem->setBackground(QColor(200, 255, 200));
        } else {
            profitItem->setBackground(QColor(255, 200, 200));
        }

        // 添加到表格
        m_tradesTable->setItem(i, 0, timeItem);
        m_tradesTable->setItem(i, 1, typeItem);
        m_tradesTable->setItem(i, 2, priceItem);
        m_tradesTable->setItem(i, 3, amountItem);
        m_tradesTable->setItem(i, 4, totalItem);
        m_tradesTable->setItem(i, 5, balanceItem);
        m_tradesTable->setItem(i, 6, profitItem);
    }
}

void BackTestWidget::updateResults()
{
    const auto& trades = m_backtestEngine->getTrades();
    if (trades.isEmpty()) {
        m_resultsText->setText("没有交易记录");
        return;
    }

    double initialBalance = m_initialBalanceSpin->value();
    double finalBalance = m_backtestEngine->getFinalBalance();
    double totalReturn = m_backtestEngine->getTotalReturn();
    double totalProfit = finalBalance - initialBalance;

    // 计算交易统计
    int winCount = 0, loseCount = 0;
    double totalWin = 0, totalLoss = 0;

    for (int i = 1; i < trades.size(); i++) {
        double tradeProfit = trades[i].balance - trades[i-1].balance;
        if (tradeProfit > 0) {
            winCount++;
            totalWin += tradeProfit;
        } else {
            loseCount++;
            totalLoss += tradeProfit;
        }
    }

    double winRate = (winCount + loseCount) > 0 ?
                         (double)winCount / (winCount + loseCount) * 100 : 0;
    double profitFactor = totalLoss != 0 ? std::abs(totalWin / totalLoss) : 0;

    // 计算最大回撤
    double maxBalance = initialBalance;
    double maxDrawdown = 0;

    for (const auto& trade : trades) {
        if (trade.balance > maxBalance) {
            maxBalance = trade.balance;
        }
        double drawdown = (maxBalance - trade.balance) / maxBalance * 100;
        if (drawdown > maxDrawdown) {
            maxDrawdown = drawdown;
        }
    }

    QString resultText =
        "═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════\n"
        "                                                                                                        回测结果统计                   \n"
        "═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════\n\n"
        "                                                                                                                                       📊 资金统计:\n"
        "                                                                                                        初始资金: " + QString::number(initialBalance, 'f', 2) + " USD\n" +
        "                                                                                                        最终资金: " + QString::number(finalBalance, 'f', 2) + " USD\n" +
        "                                                                                                        总利润: " + QString::number(totalProfit, 'f', 2) + " USD\n" +
        "                                                                                                        总收益率: " + QString::number(totalReturn, 'f', 2) + "%\n\n"
        "                                                                                                        📈 交易统计:\n"
        "                                                                                                        总交易次数: " + QString::number(trades.size()) + "\n" +
        "                                                                                                        盈利次数: " + QString::number(winCount) + "\n" +
        "                                                                                                        亏损次数: " + QString::number(loseCount) + "\n" +
        "                                                                                                        胜率: " + QString::number(winRate, 'f', 2) + "%\n" +
        "                                                                                                        利润因子: " + QString::number(profitFactor, 'f', 2) + "\n\n"
        "                                                                                                        ⚠️ 风险指标:\n"
        "                                                                                                        最大回撤: " + QString::number(maxDrawdown, 'f', 2) + "%\n\n"
        "═════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════\n";

    m_resultsText->setText(resultText);
}

void BackTestWidget::selectStrategy(int index)
{
    if(index==0){

        m_backtestEngine->setStrategy(m_strategy);

    }else if(index==1){
        m_backtestEngine->setStrategy(m_minStrategy);
         std::cout<<"select Mine strategy"<<std::endl;
    }
}


